package com.duing.handler;

import com.duing.bean.DataBean;
import com.duing.service.DataService;
import com.duing.util.HttpURLConnectUtil;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

// 使用组件注解  将bean托管到spring容器中
//  没有明确的职责划分的组件  使用此注解
@Component
public class DataHandler {

    @Autowired
    private DataService dataService;

    //数据初始化
    //  在服务器启加载Servlet时运行 且 只执行一次
    @PostConstruct
    public void saveData(){
        List<DataBean> dataBeans = getData();
        // mybatis-plus提供了可用的方法
        // 删除全部数据  批量新增数据
        dataService.remove(null);
        dataService.saveBatch(dataBeans);
    }

    private static SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    //实时更新数据（定时更新）
    @Scheduled(cron = "0 0 0/1 * * ? ")
    public void updateDate(){
        System.out.println("要更新数据啦");
        System.out.println("当前时间：" + dateFormat.format(new Date()));

        List<DataBean> dataBeans = getData();
        dataService.remove(null);
        dataService.saveBatch(dataBeans);
    }

//    private static String testStr = "{\"name\":\"duyi\"}";

    private static String url = "https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5";

//    public static void main(String[] args) throws Exception{
//        Gson gson = new Gson();
//        Map map = gson.fromJson(testStr, Map.class);
//        System.out.println(map);

//        //类加载器的所有路径
//        System.out.println(ClassLoader.getSystemClassLoader().getSystemResource(""));
//        System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));
//        //项目所在的路径
//        System.out.println(System.getProperty("user.dir"));

//        getData();
//    }


    //读取文件中的json数据  使用gson转化成需要的格式
    public static List<DataBean> getData(){

        List<DataBean> result = new ArrayList<>();

        try {
            // 先通过io  读取数据
//            FileReader fr = new FileReader("tmp.txt");
//            char[] cBuf = new char[1024];
//            int cRead = 0;//读取得进度
//            // 通过StringBuilder拼接每次读到得数据
//            StringBuilder builder = new StringBuilder();
//            while ((cRead = fr.read(cBuf)) > 0) {
//                builder.append(new String(cBuf, 0, cRead));
//            }
//            fr.close();
//        System.out.println(builder.toString());

            String str = HttpURLConnectUtil.doGet(url);

            // 再通过gson  解析数据
            Gson gson = new Gson();
            // map包含两个key ret  data =》 data的数据类型是String
            Map strMap = gson.fromJson(str, Map.class);
            String subMap = (String)strMap.get("data");

            // 此时和tmp.txt  内容一致
            Map map = gson.fromJson(subMap, Map.class);
//          System.out.println(map);

            ArrayList areaList = (ArrayList) map.get("areaTree");
            Map dataMap = (Map) areaList.get(0);
            ArrayList childrenList = (ArrayList) dataMap.get("children");
//            System.out.println(childrenList);


            for (int i = 0; i < childrenList.size(); i++) {
                //获取 地区名字
                Map tmp = (Map) childrenList.get(i);
                String name = (String) tmp.get("name");
                //获取 累计确诊人数  现有确诊人数  死亡人数  治愈人数
                Map totalMap = (Map) tmp.get("total");
                double confirm = (Double) totalMap.get("confirm");
                double nowConfirm = (Double) totalMap.get("nowConfirm");
                double dead = (Double) totalMap.get("dead");
                double heal = (Double) totalMap.get("heal");
                //将每次获取到得数据包装成对象
                DataBean dataBean = new DataBean(0L,name, (int) confirm, (int) nowConfirm, (int) dead, (int) heal);
                //返回一堆对象数据
                result.add(dataBean);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
//        System.out.println(result);
        return result;
    }
}
